//
//  OrderDetailViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/13.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "OrderCountCell.h"
#import "OrderPayViewController.h"
#import "AddressModel.h"

@interface OrderDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *people;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;
@property (weak, nonatomic) IBOutlet UILabel *address;
@property (weak, nonatomic) IBOutlet UILabel *orderTime;
@property (weak, nonatomic) IBOutlet UIImageView *productImage;
@property (weak, nonatomic) IBOutlet UILabel *productName;
@property (weak, nonatomic) IBOutlet UILabel *unitPrice;
@property (weak, nonatomic) IBOutlet UILabel *orderNumber;
@property (weak, nonatomic) IBOutlet UILabel *productNumber;
@property (weak, nonatomic) IBOutlet UILabel *count;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray *designArray;
@property (strong, nonatomic) BulkorderModel *orderModel;
@property (strong, nonatomic) AddressModel *addressModel;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;

@end

@implementation OrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _orderTitle;
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestData {
    if (_shoppingcartId) {
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"shoppingcartId":_shoppingcartId==nil?@"":_shoppingcartId};
        [RequestData queryShoppingCartParameters:[UIUtil toJsonString:dic] withBlock:^(BulkorderModel *model, NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                self.orderModel = model;
            }
        }];
    } else {
        self.orderModel = _bulkorderModel;
    }
}

- (void)setOrderModel:(BulkorderModel *)orderModel {
    _orderModel = orderModel;
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken,@"addressId":_orderModel.userReceiveAddress==nil?@"":_orderModel.userReceiveAddress};
    [RequestData queryAddressList:[UIUtil toJsonString:dic] withBlock:^(NSArray *array, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            self.addressModel = array[0];
            NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"productId":_orderModel.productId==nil?@"":_orderModel.productId};
            [RequestData getProductDetail:[UIUtil toJsonString:dic] withBlock:^(ProductDetailModel *model, NSString *msg, NSError *error) {
                if (error) {
                    if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                        [UIUtil tokenOverdue:self msg:msg];
                    } else {
                        [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                } else {
                    self.productDetailModel = model;
                    [self.myTableView reloadData];
                }
            }];
        }
    }];
}

- (void)setAddressModel:(AddressModel *)addressModel {
    _addressModel = addressModel;
    if (_ifPay) {
        [_submitButton setTitle:@"立即付款" forState:UIControlStateNormal];
    }
    self.address.text = [NSString stringWithFormat:@"%@ %@ %@ %@",_addressModel.province,_addressModel.city,_addressModel.district,_addressModel.address];
    self.phoneNumber.text = _addressModel.cellPhone;
    _people.text = [NSString stringWithFormat:@"收货人:%@",_addressModel.name];

    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:_orderModel.numList.count];
    for (int i=0; i<_orderModel.numList.count; i++) {
        [array addObject:[NSString stringWithFormat:@"%@/%@",[_orderModel.numList[i] valueForKey:@"color"],[_orderModel.numList[i] valueForKey:@"size"]]];
    }
    self.style = array;
    [_productImage setImageWithURL:[NSURL URLWithString:[UIUtil containString:_orderModel.mainImage]] placeholderImage:[UIImage imageNamed:@"tupian"]];
    _productName.text = _orderModel.productName;
    _unitPrice.text = [NSString stringWithFormat:@"总价:%@",_orderModel.totalPrice];
    //    _orderNumber.text = [NSString stringWithFormat:@"订单号%@",_bulkorderModel.orderId];
    _productNumber.text = [NSString stringWithFormat:@"产品编号:%@",_orderModel.productId];
    _count.text = [NSString stringWithFormat:@"数量:%@",_orderModel.totalQuantity];
    self.designArray = [NSMutableArray arrayWithArray:_orderModel.numList];
}

#pragma mark - action methods
- (IBAction)sureButton:(id)sender {
    if (self.ifPay) {//产品详情点击立即付款
        if ([_bulkorderModel.totalQuantity integerValue] - [_productDetailModel.minOrderNumber integerValue]<0) {
            [[ESHUDView sharedInstance] showErrorMessage:[NSString stringWithFormat:@"最小下单数量不得少于%@", _productDetailModel.minOrderNumber] dismissBlock:nil];
            return;
        }
        _bulkorderModel.numList = nil;
        _bulkorderModel.imageList = nil;
        _bulkorderModel.mainImage = nil;
        [ESHUDView showLoading];
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                              @"token":[UserModel sharedInstance].userToken,
                              @"SCRecord":@{ @"productId":_bulkorderModel.productId==nil?@"":_bulkorderModel.productId,
                                             @"productName":_bulkorderModel.productName==nil?@"":_bulkorderModel.productName,
                                             @"totalQuantity":_bulkorderModel.totalQuantity==nil?@"":_bulkorderModel.totalQuantity,
                                             @"perPrice":_bulkorderModel.perPrice==nil?@"":_bulkorderModel.perPrice,
                                             @"totalPrice":_bulkorderModel.totalPrice==nil?@"":_bulkorderModel.totalPrice,
                                             @"requiredExplain":_bulkorderModel.requiredExplain==nil?@"":_bulkorderModel.requiredExplain,
                                             @"deliveryTime":_bulkorderModel.deliveryTime==nil?@"":_bulkorderModel.deliveryTime,
                                             @"deliveryWay":_bulkorderModel.deliveryWay==nil?@"":_bulkorderModel.deliveryWay,
                                             @"userReceiveAddress":_bulkorderModel.userReceiveAddress==nil?@"":_bulkorderModel.userReceiveAddress},
                              @"dataList":self.designArray==nil?@"":self.designArray};
        [RequestData bulkorderParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *bulkorderId, NSString *toPayId, NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交大货单失败":msg dismissBlock:nil];
                }
            } else {
                [ESHUDView dismiss];
                OrderPayViewController *view = [[OrderPayViewController alloc] init];
                view.toPayId = toPayId;
                [self.navigationController pushViewController:view animated:YES];
            }
        }];
    } else {
        NSInteger count = 0;
        for (int i=0; i<self.designArray.count; i++) {
            count = count + [[self.designArray[i] valueForKey:@"quantity"] integerValue];
        }
        NSString *price = [self.productDetailModel.optOrderNumber integerValue] - count > 0 ?self.productDetailModel.quotation:self.productDetailModel.quotation2;
        _orderModel.perPrice = price;
        _orderModel.totalPrice = [NSString stringWithFormat:@"%.2f",[price floatValue]*count];
        _orderModel.totalQuantity = [NSString stringWithFormat:@"%li", (long)count];
        [ESHUDView showLoading];
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                              @"token":[UserModel sharedInstance].userToken,
                              @"type":@"2",
                              @"SCRecord":@{ @"id":_shoppingcartId==nil?@"":_shoppingcartId,
                                             @"productId":_productDetailModel.productId==nil?@"":_productDetailModel.productId,
                                             @"productName":_productDetailModel.productName==nil?@"":_productDetailModel.productName,
                                             @"totalQuantity":[NSString stringWithFormat:@"%li", (long)count],
                                             @"perPrice":price==nil?@"":price,
                                             @"totalPrice":[NSString stringWithFormat:@"%.2f",[price floatValue]*count],
                                             @"requiredExplain":_orderModel.requiredExplain==nil?@"":_orderModel.requiredExplain,
                                             @"deliveryTime":_orderModel.deliveryTime==nil?@"":_orderModel.deliveryTime,
                                             @"deliveryWay":_orderModel.deliveryWay==nil?@"":_orderModel.deliveryWay,
                                             @"remark":@"beizhu",
                                             @"userReceiveAddress":_orderModel.userReceiveAddress==nil?@"":_orderModel.userReceiveAddress},
                              @"dataList":self.designArray};
        [RequestData addShoppingCart:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"修改订单失败":msg dismissBlock:nil];
                }
            } else {
                [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.style.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *orderDetailCellIdentifier = @"OrderCountCell";
    [self.myTableView registerNib:[UINib nibWithNibName:@"OrderCountCell" bundle:nil]
           forCellReuseIdentifier:orderDetailCellIdentifier];
    OrderCountCell *cell = [tableView dequeueReusableCellWithIdentifier:orderDetailCellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.countString = [[_designArray objectAtIndex:indexPath.row] valueForKey:@"quantity"];
    cell.styleString = self.style[indexPath.row];
    cell.index = indexPath.row;
    cell.orderCountBlock =^(NSInteger index, NSString *count) {
        [_designArray replaceObjectAtIndex:index withObject:@{@"color":[_designArray[index] valueForKey:@"color"], @"size":[_designArray[index] valueForKey:@"size"], @"quantity":count}];
        [self changeData];
    };
    return cell;
}

- (void)changeData {
    NSInteger count = 0;
    for (int i=0; i<self.designArray.count; i++) {
        count = count + [[self.designArray[i] valueForKey:@"quantity"] integerValue];
    }
    NSString *price = [self.productDetailModel.optOrderNumber integerValue] - count > 0 ?self.productDetailModel.quotation:self.productDetailModel.quotation2;
    _orderModel.perPrice = price;
    _orderModel.totalPrice = [NSString stringWithFormat:@"%.2f",[price floatValue]*count];
    _orderModel.totalQuantity = [NSString stringWithFormat:@"%ld", (long)count];
    self.count.text = [NSString stringWithFormat:@"数量:%@", _orderModel.totalQuantity];
    self.unitPrice.text = [NSString stringWithFormat:@"总价:%@",_orderModel.totalPrice];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
